package com.cloudwave.trailends.ui;

import java.util.ArrayList;
import java.util.List;

import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.WindowManager;
import android.widget.Toast;

import com.cloudwave.trailends.Constants;
import com.cloudwave.trailends.R;
import com.cloudwave.trailends.domain.LinePoint;
import com.cloudwave.trailends.domain.RidingLine;
import com.cloudwave.trailends.utils.CollectionUtils;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.Legend.LegendForm;
import com.github.mikephil.charting.components.Legend.LegendPosition;
import com.github.mikephil.charting.components.LimitLine;
import com.github.mikephil.charting.components.LimitLine.LimitLabelPosition;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.XAxis.XAxisPosition;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.exception.DbException;

/**
 * @author 龙雪
 * 2015-3-17
 */

public class DetailChartActivity extends FragmentActivity {
	private final static String TAG = "DetailChartActivity";
	
	private LineChart mChart;
	
	 @Override
	    protected void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);
	        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
	                WindowManager.LayoutParams.FLAG_FULLSCREEN);
	        setContentView(R.layout.detail_chart);
	        
	        mChart = (LineChart) findViewById(R.id.chart1);
//	        mChart.setOnChartValueSelectedListener(this);
	        
	       // no description text
	        mChart.setDescription("描述");
	        mChart.setNoDataTextDescription("没有数据");

	        // enable value highlighting
	        mChart.setHighlightEnabled(true);
	        
	       // enable touch gestures
	        mChart.setTouchEnabled(true);

	        // enable scaling and dragging
	        mChart.setDragEnabled(true);
	        mChart.setScaleEnabled(true);
	        mChart.setDrawGridBackground(false);
	        
	       // if disabled, scaling can be done on x- and y-axis separately
	        mChart.setPinchZoom(true);

	        // set an alternative background color
	        mChart.setBackgroundColor(Color.LTGRAY);
	        
	        loadData();
	        
//	        Typeface tf = Typeface.createFromAsset(getAssets(), "OpenSans-Regular.ttf");

	        // get the legend (only possible after setting data)
	        Legend l = mChart.getLegend();

	        // modify the legend ...
	        // l.setPosition(LegendPosition.LEFT_OF_CHART);
	        l.setForm(LegendForm.LINE);
//	        l.setTypeface(tf);
	        l.setTextSize(11f);
	        l.setTextColor(Color.WHITE);
	        l.setPosition(LegendPosition.BELOW_CHART_LEFT);

	        XAxis xAxis = mChart.getXAxis();
	        xAxis.setPosition(XAxisPosition.BOTTOM);
//	        xAxis.setTypeface(tf);
	        xAxis.setTextSize(12f);
	        xAxis.setTextColor(Color.WHITE);
	        xAxis.setDrawGridLines(false);
	        xAxis.setDrawAxisLine(true);
	        xAxis.setSpaceBetweenLabels(1);

	        
	        YAxis leftAxis = mChart.getAxisLeft();
//	        leftAxis.setTypeface(tf);
	        leftAxis.setTextColor(ColorTemplate.getHoloBlue());
	        leftAxis.setDrawGridLines(true);
	        leftAxis.setAxisMaxValue(55f);
	        leftAxis.setAxisMinValue(0f);
	        leftAxis.setStartAtZero(true);
	        
	        YAxis rightAxis = mChart.getAxisRight();
//	        rightAxis.setTypeface(tf);
//	        rightAxis.setTextColor(ColorTemplate.getHoloBlue());
	        rightAxis.setTextColor(Color.BLUE);
	        rightAxis.setAxisMaxValue(55f);
	        rightAxis.setStartAtZero(true);
	        rightAxis.setAxisMinValue(0f);
	        rightAxis.setDrawGridLines(false);
	        rightAxis.setEnabled(true);
	 }
	 
	 private void loadData() {
		 DbUtils dbu = DbUtils.create(this, Constants.DB_NAME);
		 Long id = getIntent().getLongExtra("rlId", 0);
		 RidingLine rl = null;
		 try {
			 rl = dbu.findById(RidingLine.class, id);
		} catch (DbException e) {
			Toast.makeText(DetailChartActivity.this, "数据加载失败~_~", Toast.LENGTH_SHORT).show();
			Log.e(TAG, "查询记录数据异常:", e);
			return ;
		}
		 
		 List<LinePoint> lList = null;
		try {
			 lList = dbu.findAll(Selector.from(LinePoint.class).where("ridingline_id", "==", id)
					 .where("speed_", ">", 0).orderBy("createtime_"));
		} catch (DbException e) {
			Toast.makeText(DetailChartActivity.this, "数据加载失败~_~", Toast.LENGTH_SHORT).show();
			Log.e(TAG, "查询记录数据异常:", e);
			return ;
		}
		
		if ( CollectionUtils.isEmpty(lList) ) {
			Toast.makeText(DetailChartActivity.this, "记录为空", Toast.LENGTH_SHORT).show();
			return ;
		}
		
		ArrayList<String> xVals = new ArrayList<String>();
		ArrayList<Entry> yVals = new ArrayList<Entry>();
		
		int size = lList.size();
		int step = size / 100;
		
		for ( int i=0; i<=step; i++ ) {
			float speed = 0;
			for ( int j=i*step; j<(i+1)*step; j++ ) {
				LinePoint lp = lList.get(j);
				speed += lp.getSpeed();
			}
			float avgSpeed = speed / (float) step;
			
			xVals.add(i+"");
			yVals.add(new Entry(avgSpeed, i));
		}
		
		
		for ( int i=0; i<lList.size(); i++ ) {
			LinePoint lp = lList.get(i);
//			xVals.add(lp.getDistance().toString());
			xVals.add(i+"");
			yVals.add(new Entry(lp.getSpeed(), i));
		}
		
		LineDataSet setSpeed = new LineDataSet(yVals, "速度");
//		setSpeed.setColor(Color.YELLOW);
//		setSpeed.setLineWidth(1f);
////		setSpeed.enableDashedLine(10f, 5f, 0f);
////		setSpeed.setCircleColor(Color.BLUE);
////		setSpeed.setCircleSize(3f);
//		setSpeed.setDrawCircleHole(false);
//		setSpeed.setValueTextSize(9f);
//		setSpeed.setFillAlpha(65);
//		setSpeed.setFillColor(Color.BLUE);
        
		setSpeed.setDrawCubic(true);
		setSpeed.setCubicIntensity(0.2f);
        //set1.setDrawFilled(true);
		setSpeed.setDrawCircles(false); 
		setSpeed.setLineWidth(2f);
		setSpeed.setCircleSize(5f);
		setSpeed.setHighLightColor(Color.rgb(244, 117, 117));
		setSpeed.setColor(Color.rgb(104, 241, 175));
		setSpeed.setFillColor(ColorTemplate.getHoloBlue());
        
        ArrayList<LineDataSet> dataSets = new ArrayList<LineDataSet>();
        dataSets.add(setSpeed); // add the datasets

        // create a data object with the datasets
        LineData data = new LineData(xVals, dataSets);
        
        LimitLine avgSpeedLine = new LimitLine(rl.getAvgSpeed(), "平均速度");
        avgSpeedLine.setLineWidth(2f);
        avgSpeedLine.enableDashedLine(10f, 10f, 0f);
        avgSpeedLine.setLabelPosition(LimitLabelPosition.POS_RIGHT);
        avgSpeedLine.setTextSize(10f);
//        mChart.getAxisLeft().addLimitLine(avgSpeedLine);
        
        // set data
        mChart.setData(data);
        
        mChart.animateX(1000);
	 }
}
